package com.flyou.ccnucenter.ui.activity.account;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadListener;
import com.e1858.myalertview.AlertView;
import com.e1858.myalertview.OnItemClickListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.flyou.ccnucenter.Constant;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.domain.MyUser;
import com.flyou.ccnucenter.ui.activity.BaseActivity1;
import com.flyou.ccnucenter.utils.BitmapUtil;
import com.flyou.ccnucenter.utils.BmobErrorCodeUtils;
import com.flyou.ccnucenter.utils.LoginUtils;
import com.flyou.ccnucenter.utils.SDCardUtils;
import com.flyou.ccnucenter.utils.SPUtils;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;

public class MyAccountActivity extends BaseActivity1 implements View.OnClickListener, OnItemClickListener {
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    /* 头像名称 */
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private TextView mTvPhoneNum;
    private File tempFile;
    private AlertView mAlertView;
    private RelativeLayout mTitlebarRlBack;
    private TextView mTitlebarTvTitle;
    private SimpleDraweeView mUserHeadeBg;
    private TextView mTvNickname;
    private TextView mTvChangePassword;
    private TextView mTvGrade;
    private TextView mTvDepartment;
    private TextView mTvEmail;
    private String[] gradeArray;

    private LinearLayout mLlChangeHenadImage, mLlChangeNickName, mLlChangeGrade, mLlChangeDepartment, mLlChangeEmail;


    @Override
    protected void initView() {
        setContentView(R.layout.activity_my_account);
        mTitlebarRlBack = (RelativeLayout) findViewById(R.id.titlebar_rl_back);
        mTitlebarTvTitle = (TextView) findViewById(R.id.titlebar_tv_title);
        mUserHeadeBg = (SimpleDraweeView) findViewById(R.id.user_header_bg);
        mTvNickname = (TextView) findViewById(R.id.tv_nickname);
        mTvChangePassword = (TextView) findViewById(R.id.tv_change_password);
        mTvPhoneNum = (TextView) findViewById(R.id.tv_phone_num);
        mTvGrade = (TextView) findViewById(R.id.tv_grade);
        mTvDepartment = (TextView) findViewById(R.id.tv_department);
        mTvEmail = (TextView) findViewById(R.id.tv_email);

        mLlChangeHenadImage = (LinearLayout) findViewById(R.id.ll_change_henadImage);
        mLlChangeNickName = (LinearLayout) findViewById(R.id.ll_change_nickName);
        mLlChangeGrade = (LinearLayout) findViewById(R.id.ll_change_grade);
        mLlChangeDepartment = (LinearLayout) findViewById(R.id.ll_change_department);
        mLlChangeEmail = (LinearLayout) findViewById(R.id.ll_change_email);


        String headImage = (String) SPUtils.get(MyAccountActivity.this, "headImage", "");
        if (!TextUtils.isEmpty(headImage)) {
            mUserHeadeBg.setImageURI(Uri.parse(headImage));
        }
        String userName = (String) SPUtils.get(MyAccountActivity.this, "userName", "");
        if (!TextUtils.isEmpty(userName)) {
            mTvNickname.setText(userName);
        }
        String phone = (String) SPUtils.get(MyAccountActivity.this, "phone", "");
        if (!TextUtils.isEmpty(phone)) {
            mTvPhoneNum.setText(phone.substring(0, 3));
            mTvPhoneNum.append("****");
            mTvPhoneNum.append(phone, 7, 11);
        }
        String email = (String) SPUtils.get(MyAccountActivity.this, "email", "");
        if (!TextUtils.isEmpty(email)) {
            mTvEmail.setText(email);
        }
        String department = (String) SPUtils.get(MyAccountActivity.this, "department", "");
        if (!TextUtils.isEmpty(department)) {
            mTvDepartment.setText(department);
        }
        String grade = (String) SPUtils.get(MyAccountActivity.this, "grade", "");
        if (!TextUtils.isEmpty(grade)) {
            mTvGrade.setText(grade + "级");
        }

    }

    @Override
    protected void initDate() {
        mTitlebarTvTitle.setText("我的账户");
        Calendar calendar = new GregorianCalendar();
        int gradeYear = calendar.get(Calendar.YEAR) - 2008;
        gradeArray = new String[gradeYear];
        for (int i = 0; i < gradeYear; i++) {
            gradeArray[i] = (2008 + i) + "";
        }
    }

    @Override
    protected void setListener() {
        mTitlebarRlBack.setOnClickListener(this);
        mTvChangePassword.setOnClickListener(this);
        mLlChangeHenadImage.setOnClickListener(this);
        mLlChangeNickName.setOnClickListener(this);
        mLlChangeGrade.setOnClickListener(this);
        mLlChangeDepartment.setOnClickListener(this);
        mLlChangeEmail.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_rl_back:
                finish();
                break;
            case R.id.ll_change_henadImage:
                mAlertView = new AlertView("上传头像", null, "取消", null, new String[]{"拍照", "从手机相册选择"}, this, AlertView.Style.ActionSheet, this);
                mAlertView.show();
                break;
            case R.id.ll_change_nickName:
                Intent changeNickNameIntent = new Intent(MyAccountActivity.this, ChangeNickNameActivity.class);
                startActivity(changeNickNameIntent);

                break;
            case R.id.tv_change_password:
                Intent changePasswordIntent = new Intent(MyAccountActivity.this, ChangePasswordActivity.class);
                startActivity(changePasswordIntent);
                break;
            case R.id.ll_change_grade:
                mAlertView = new AlertView("选择年级", null, "取消", null, gradeArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, final int position) {
                        if (position==-1){
                            return;
                        }
                        MyUser myUser = new MyUser();
                        mTvGrade.setText(gradeArray[position] + "级");
                        MyUser currentUser = BmobUser.getCurrentUser(MyAccountActivity.this, MyUser.class);
                        myUser.setGrade(gradeArray[position]);
                        myUser.update(MyAccountActivity.this, currentUser.getObjectId(), new UpdateListener() {
                            @Override
                            public void onSuccess() {
                                Toast.makeText(MyAccountActivity.this, "设置年级成功", Toast.LENGTH_SHORT).show();
                                SPUtils.put(MyAccountActivity.this, "grade", gradeArray[position]);
                            }

                            @Override
                            public void onFailure(int i, String s) {
                                Toast.makeText(MyAccountActivity.this, BmobErrorCodeUtils.getMessage(i, s), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
                mAlertView.show();
                break;
            case R.id.ll_change_department:
                mAlertView = new AlertView("选择院系", null, "取消", null, Constant.DEPARTMENTARRAY, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, final int position) {
                        if (position==-1){
                            return;
                        }
                        MyUser myUser = new MyUser();
                        mTvDepartment.setText(Constant.DEPARTMENTARRAY[position]);
                        final MyUser currentUser = BmobUser.getCurrentUser(MyAccountActivity.this, MyUser.class);
                        myUser.setDepartment(Constant.DEPARTMENTARRAY[position]);
                        myUser.update(MyAccountActivity.this, currentUser.getObjectId(), new UpdateListener() {
                            @Override
                            public void onSuccess() {
                                Toast.makeText(MyAccountActivity.this, "设置院系成功", Toast.LENGTH_SHORT).show();

                                SPUtils.put(MyAccountActivity.this, "department", Constant.DEPARTMENTARRAY[position]);
                            }

                            @Override
                            public void onFailure(int i, String s) {
                                Toast.makeText(MyAccountActivity.this, BmobErrorCodeUtils.getMessage(i, s), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
                mAlertView.show();
                break;
            case R.id.ll_change_email:
                Intent changeEmailIntent = new Intent(MyAccountActivity.this, ChangeEmailActivity.class);
                startActivity(changeEmailIntent);

                break;

        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        switch (position) {
            // TODO: 2015/10/27 拍照及从相册获取后上传服务器逻辑处理
            case 0:
                Toast.makeText(this, "拍照", Toast.LENGTH_SHORT).show();
                getPhotoFromCamera();
                break;
            case 1:
                Toast.makeText(this, "从手机相册选取", Toast.LENGTH_SHORT).show();
                getPhotoFromGallery();

                break;
        }
    }
//、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
//、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、拍照与获取手机相册的逻辑、、、、、、、、、、、、、、、、、、、、、、、、
//、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (mAlertView != null && mAlertView.isShowing()) {
                mAlertView.dismiss();
                return false;
            }
        }

        return super.onKeyDown(keyCode, event);

    }

    /*
     * 判断sdcard是否被挂载
     */
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /*
  * 判断文件是否存在
  */
    public static void isExist(String path) {
        File file = new File(path);
//判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists()) {
            file.mkdir();
        }
    }

    /*
   * 从相册获取
   */
    public void getPhotoFromGallery() {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    /*
     * 从相机获取
     */
    public void getPhotoFromCamera() {
        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            isExist(Environment.getExternalStorageDirectory() + File.separator + "flyou");

            tempFile = new File(Environment.getExternalStorageDirectory() + File.separator + "flyou",
                    PHOTO_FILE_NAME);
            // 从文件中创建uri
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }

    /*
     * 剪切图片
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            // 从相机返回的数据
            if (hasSdcard()) {
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(MyAccountActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {
                mProgressDialog = ProgressDialog.show(MyAccountActivity.this, null, "正在上传头像", false, false);
                Bitmap bitmap = data.getParcelableExtra("data");

                isExist(SDCardUtils.getSDCardPath() + File.separator + "flyou");
                final File file = new File(SDCardUtils.getSDCardPath() + File.separator + "flyou", LoginUtils.getUserId(MyAccountActivity.this)+System.currentTimeMillis() + ".jpg");
                BitmapUtil.saveBitmap(bitmap, file);
                BmobProFile.getInstance(MyAccountActivity.this).upload(file.getAbsolutePath(), new UploadListener() {
                    @Override
                    public void onSuccess(String fileName, String url, final BmobFile bmobFile) {
                        SPUtils.put(MyAccountActivity.this, "headImage", bmobFile.getUrl());

                        MyUser bmobMyUser = MyUser.getCurrentUser(MyAccountActivity.this, MyUser.class);
                        MyUser myUser = new MyUser();
                        myUser.setHeadImage(bmobFile.getUrl());
                        myUser.update(MyAccountActivity.this, bmobMyUser.getObjectId(), new UpdateListener() {
                            @Override
                            public void onFinish() {
                                mProgressDialog.dismiss();
                                super.onFinish();
                            }

                            @Override
                            public void onSuccess() {
                                EventBus.getDefault().post("", Constant.UPDATE_HEADIMAGE);
                                Toast.makeText(MyAccountActivity.this, "头像修改成功", Toast.LENGTH_SHORT).show();
                                mUserHeadeBg.setImageURI(Uri.parse(bmobFile.getUrl()));

                            }

                            @Override
                            public void onFailure(int i, String s) {

                                String message = BmobErrorCodeUtils.getMessage(i, s);
                                Toast.makeText(MyAccountActivity.this, "修改头像失败：" + message, Toast.LENGTH_SHORT).show();
                            }
                        });
//                            删除本地头像文件
                        file.delete();
                    }

                    @Override
                    public void onProgress(int i) {

                    }

                    @Override
                    public void onError(int i, String s) {
                        String message = BmobErrorCodeUtils.getMessage(i, s);
                        Toast.makeText(MyAccountActivity.this, "修改头像失败：" + message, Toast.LENGTH_SHORT).show();
                    }
                });
            }
            try {
                // 将临时文件删除
                tempFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mUserHeadeBg==null||mTvNickname==null||mTvPhoneNum==null||mTvEmail==null||mTvDepartment==null||mTvGrade==null){
            return;
        }
        String headImage = (String) SPUtils.get(MyAccountActivity.this, "headImage", "");
        if (!TextUtils.isEmpty(headImage)) {
            mUserHeadeBg.setImageURI(Uri.parse(headImage));
        }
        String userName = (String) SPUtils.get(MyAccountActivity.this, "userName", "");
        if (!TextUtils.isEmpty(userName)) {
            mTvNickname.setText(userName);
        }
        String phone = (String) SPUtils.get(MyAccountActivity.this, "phone", "");
        if (!TextUtils.isEmpty(phone)) {
            mTvPhoneNum.setText(phone.substring(0, 3));
            mTvPhoneNum.append("****");
            mTvPhoneNum.append(phone, 7, 11);
        }
        String email = (String) SPUtils.get(MyAccountActivity.this, "email", "");
        if (!TextUtils.isEmpty(email)) {
            mTvEmail.setText(email);
        }
        String department = (String) SPUtils.get(MyAccountActivity.this, "department", "");
        if (!TextUtils.isEmpty(department)) {
            mTvDepartment.setText(department);
        }
        String grade = (String) SPUtils.get(MyAccountActivity.this, "grade", "");
        if (!TextUtils.isEmpty(grade)) {
            mTvGrade.setText(grade + "级");
        }
    }
}